#include <iostream>
#include <functional>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include "log.hpp"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
namespace MY
{
    using func_t = std::function<std::string(const std::string &)>;
    const int defaultSocketId = -1;
    class udpServer
    {
    private:
        int _socketid;
        uint16_t _port;
        bool _isrunning;
        func_t _func;

    public:
        udpServer(uint16_t, func_t);
        ~udpServer();
        void start();
    };

    udpServer::udpServer(uint16_t port, func_t func)
        : _socketid(defaultSocketId), _port(port), _isrunning(false), _func(func)
    {
        _socketid = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketid == -1)
        {
            MY::LOG(MY::logLevel::FATAL) << "socket fail";
            exit(1);
        }
        MY::LOG(MY::logLevel::INFO) << "socket success";
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        int n = bind(_socketid, (sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            MY::LOG(MY::logLevel::FATAL) << "bind fail";
            exit(2);
        }
        MY::LOG(MY::logLevel::INFO) << "bind success,sockfd: " << _socketid;
    }

    udpServer::~udpServer()
    {
    }
    inline void udpServer::start()
    {
        MY::LOG(MY::logLevel::INFO) << "server start to listen";
        _isrunning = true;
        while (_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t s = recvfrom(_socketid, buffer, sizeof(buffer), 0, (sockaddr *)&peer, &len);
            if (s > 0)
            {
                // MY::LOG(MY::logLevel::INFO) << "recvfrom success";
                int peer_port = ntohs(peer.sin_port);
                std::string peer_ip = inet_ntoa(peer.sin_addr);
                buffer[s] = 0;
                std::string result = _func(buffer);
                MY::LOG(MY::logLevel::INFO) << '[' << peer_ip << ']' << "say :" << buffer;
                sendto(_socketid, result.c_str(), result.size(), 0, (sockaddr *)&peer, len);
            }
        }
    }
}